package com.wanyang.service;

import com.wanyang.dos.MemberDO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class JwtTokenHelper {
    public static final String CLAIM_KEY_USERID = "sub";
    public static final String CLAIM_KEY_CREATED = "created";
    public static final String CLAIM_KEY_TYPE = "type";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.refreshTokenExpiration}")
    private Long refreshTokenExpiration;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            return e.getClaims();
        } catch (Exception e) {
            log.error("JWT格式验证失败:{}", token);
            throw new RuntimeException(e);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public Integer getUserIdFromToken(String token) {
        Integer memberId;
        try {
            Claims claims = getClaimsFromToken(token);
            memberId = claims.get(CLAIM_KEY_USERID, Integer.class);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return memberId;
    }


    /**
     * 判断token是否已经失效
     */
    public boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(MemberDO memberDO) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERID, memberDO.getId());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims);
    }


    public String generateRefreshToken(MemberDO memberDO) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERID, memberDO.getId());
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_TYPE, "refresh");
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + refreshTokenExpiration * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }


    public static void main(String[] args) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USERID, 1);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_TYPE, "refresh");
        System.out.println(Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + 10000000))
                .signWith(SignatureAlgorithm.HS512, "jfdklaurejklq*23")
                .compact());
    }

}